import { Col, Form, Input, Row, Typography } from 'antd'

import React, { useEffect } from 'react'
import { useState } from 'react'
import { getItem } from '../../helpers/cart'
import CarItem from './CarItem'
import Layout from './Layout'
import PayButton from './PayButton'
const { Title } = Typography

function Cart() {
  const [cart, setCart] = useState([])
  const [address, SetAddress] = useState('')
  const [totalPrice, SetTotalPrice] = useState(0)
  useEffect(() => {
    setCart(getItem())
  },[])

  useEffect(() => {
    let totalPrice = cart.reduce((currentValue,nextValue) => {
      return (currentValue += nextValue.count* nextValue.price)
    }, 0).toFixed(2)
    SetTotalPrice(totalPrice)
  },[cart])

  const cartTable = () => (
    <table style={{ width: "100%" }}>
      <thead className="ant-table-thead">
        <tr>
          <th className="ant-table-cell">商品封面</th>
          <th className="ant-table-cell">商品名称</th>
          <th className="ant-table-cell">商品价格</th>
          <th className="ant-table-cell">商品分类</th>
          <th className="ant-table-cell">商品数量</th>
          <th className="ant-table-cell">操作</th>
        </tr>
      </thead>
      <tbody className="ant-table-tbody">
        {cart.map(product => (<CarItem setCart={setCart} key={product._id} product={product}/>))}
      </tbody>
    </table>
  )
  return (
    <Layout title='购物车' subTitle='请付款~'>
      <Row gutter={16}>
        <Col span={19}>{cartTable()}</Col>
        <Col span={5}>
          <Form.Item label='收货地址'>
            <Input placeholder='请输入地址' value={address}
            onChange={(ev) => {SetAddress(ev.target.value)}} />
          </Form.Item>
          <Title level={5}>总价：{totalPrice}</Title>
          <PayButton address={address} cart={cart} totalPrice={totalPrice}/>
        </Col>
      </Row>
    </Layout>
  )
}

export default Cart